import axios from 'axios';
// import Toast from '@/components/toast'
// import env from './env'
import utils from './utils'
let isAndroid = utils.isAndroid();
let isIOS = utils.isIOS();
let axiosInst = axios.create({ timeout: 20000 });
let baseUrl = '';
let httpHeader = {}
axiosInst.install = function (Vue) {
	if (window.yryz.isNative()) {
		window.yryz.httpHeader().then(h => {
			httpHeader = h || {}
		})
	}
	// else if (process.env.NODE_ENV !== 'production') {
	// 	httpHeader = {
	// 		'User-Agent': "LoveLornApp/1 CFNetwork/975.0.3 Darwin/18.2.0",
	// 	appVersion: "1.4.0",
	// 	devId: "861962039965552",
	// 	devType: 2,
	// 	ditchCode: "default",
	// 	ip: "192.168.50.87",
	// 	refreshToken: "27CjOu2XgycA1560331325774",
	// 	tenantId: "lovelorn",
	// 	token: "lvWUaH8hGfox1560331325774",
	// 	userId: 294777405423616}
	// }
	let baseUrls = {
		'localhost': 'api-dev.yryz.com/gateway',
		'192': 'api-dev.yryz.com/gateway',
    // '192': 'api-mo.yryz.com/gateway',
		'dev': 'api-dev.yryz.com/gateway',
		'test': 'api-test.yryz.com/gateway',
		'mo': 'api-mo.yryz.com/gateway',
		'sl': 'api.yryz.com/gateway'
	};
	let match = window.location.href.match(/([A-Za-z0-9]+)?\./)

	if (match && match.length > 1 && match[1]) {
		baseUrl = baseUrls[match[1].toLowerCase()];
	} else {
		baseUrl = baseUrls['localhost'] || '';
	}
	// baseUrl = 'api-dev.yryz.com/gateway';
	// baseUrl += '/yryz';
	if (baseUrl) {
		baseUrl =	window.location.protocol + "//" + baseUrl
	}
  baseUrl = baseUrl.replace('http://', 'https://');
	this.baseUrl = baseUrl

  console.log(this.baseUrl )
	Vue.http = Vue.prototype.$http = this;
	let devType = isIOS ? 1 : (isAndroid ? 2 : 3);
	// this.defaults.headers.common['devType'] = devType;
	// this.defaults.headers.common['tenantId'] = 'lovelorn';
	// this.defaults.headers.common['appVersion'] = '1.0';
	this.interceptors.request.use(async function (config) {
		// if (!Object.keys(httpHeader).length)
		// 	httpHeader = await window.yryz.httpHeader()
		if (!config.url) {
			console.log('services请求地址出错', this, config)
		}
		config.headers.common['devType'] = devType;
		config.headers.common['tenantId'] = 'lovelorn';
		config.headers.common['appVersion'] = '1.0';
		if (config.url.indexOf('http') !== 0) {
			config.url = baseUrl + config.url;
		}
		for (let i in httpHeader) {
			config.headers.common[i] = httpHeader[i];
		}
		return config;
	});

	this.interceptors.response.use(function (res) {
		if (res.data.code !== '200') {
			console.log(res.data.msg);
		}
		return res;
	}, function (error) {
		if (window.location.href.indexOf('web.') === -1 && window.location.href.indexOf('m.') === -1) {
			if (error.message && error.message.indexOf('timeout') > -1) {
				console.log('操作超时！')
			} else {
				console.log(error.toString());
			}
		}
		return Promise.reject(error);
	});
}

export default axiosInst;
